<template>
  <div>
    <h2 class="r_title">
      数据上传
    </h2>
    <div class="p20">
      <div class="row">
        <el-button slot="trigger" type="primary" @click="uploadDialog.show=true">选择文件</el-button>
        <el-button class="ml20" icon="el-icon-upload" :loading="loading" @click="submitCheck">上传检查</el-button>
        <el-button class="ml20" icon="el-icon-download">模板下载</el-button>
        <div class="right">
          <el-button type="primary" @click="submitImport" :loading="loading">确认导入</el-button>
        </div>
      </div>
      <div class="bod mt20">
        <el-table :data="errData" ref="table_container" stripe style="width: 100%" :height="tableHeight" v-loading="loading" header-cell-class-name="table-header-cell" cell-class-name="table-cell">
          <el-table-column prop="at" label="错误位置" align="center"></el-table-column>
          <el-table-column prop="reason" label="错误原因" align="center"></el-table-column>
        </el-table>
      </div>
    </div>
    <el-dialog title="上传" :visible.sync="uploadDialog.show" width="400px">
      <el-form :rules="rules" :model="data" ref="form" label-position="left" label-width="30%" class="ml30">
        <el-form-item label="文件" prop="file">
          <el-upload action="" class="ml20" ref="upload" :auto-upload="false" :show-file-list="false" :limit="1" accept=".xlsx">
            <el-button slot="trigger" type="primary" @click="$refs['upload'].clearFiles()">选择文件</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item label="省份：" prop="province">
          <el-select class="width80" v-model="data.provinceId" placeholder="请选择省份" filterable>
            <el-option
              v-for="item in province"
              :key="item.id"
              :label="item.value"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="城市：" prop="city">
          <el-select class="width80" v-model="data.cityId" placeholder="请选择城市" filterable>
            <el-option
              v-for="item in city"
              :key="item.id"
              :label="item.value"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="试验区：" prop="area">
          <el-select class="width80" v-model="data.areaId" placeholder="请选择试验区" filterable>
            <el-option
              v-for="item in area"
              :key="item.id"
              :label="item.value"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="学校：" prop="school">
          <el-select class="width80" v-model="data.schoolId" placeholder="请选择学校" filterable>
            <el-option
              v-for="item in school"
              :key="item.id"
              :label="item.value"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="测试日期：" prop="date">
          <el-date-picker
            v-model="data.date"
            type="date"
            placeholder="选择日期">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="uploadDialog.show=false">取 消</el-button>
        <el-button type="primary" @click="submitUploadDialog">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog :title="resultDialog.title" :visible.sync="resultDialog.show" width="300px">
      <div class="center">
        <i v-if="resultDialog.result" class="el-icon-success success-icon"></i>
        <i v-else class="el-icon-error error-icon"></i>
      </div>
      <div class="flex-center mt20">
        <div class="result-text center">
          <span>新增数据</span>
          <span>{{resultDialog.insert}}</span>
        </div>
      </div>
      <div class="flex-center mt5">
        <div class="result-text center">
          <span>更新数据</span>
          <span>{{resultDialog.update}}</span>
        </div>
      </div>
      <div class="flex-center mt5">
        <div class="result-text center">
          <span>验证数据</span>
          <span>{{resultDialog.valid}}</span>
        </div>
      </div>
      <div class="flex-center mt5">
        <div class="result-text center">
          <span>新增学生</span>
          <span>{{resultDialog.insertStudent}}</span>
        </div>
      </div>
      <div class="flex-center mt5">
        <div class="result-text center">
          <span>更新学生</span>
          <span>{{resultDialog.updateStudent}}</span>
        </div>
      </div>
      <div class="flex-center mt5">
        <div class="result-text center">
          <span>免测人数</span>
          <span>{{resultDialog.exemption}}</span>
        </div>
      </div>
      <div class="flex-center mt5">
        <div class="result-text center">
          <span>缺项人数</span>
          <span>{{resultDialog.missing}}</span>
        </div>
      </div>
      <div class="flex-center mt5">
        <div class="result-text center">
          <span>导入是否有错误</span>
          <span v-if="!resultDialog.result" style="color:#F56C6C">是</span>
          <span v-else style="color:#67C23A">否</span>
        </div>
      </div>
      <div class="center mt20">
        <el-button type="primary" @click="resultDialog.show=false">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { GetProvinceList, GetCityListByProvinceId, GetAreaListByCityId, GetSchoolListByAreaId } from '../../api/select'
import { physicalImportCheck, physicalImportSubmit } from '@/api/import'
export default {
  name: 'data-upload',
  mounted () {
    this.$store.dispatch('setRoute', this.$route.path)
    GetProvinceList().then(res => {
      this.province = res.data.province
    })
    setTimeout(this.reInitTableHeight, 100)
  },
  data () {
    let validateSchoolId = (rule, value, callback) => {
      if (this.school.length === 0) {
        callback(new Error('请选择学校'))
      }
      callback()
    }
    let validateFile = (rule, value, callback) => {
      if (this.$refs['upload'].uploadFiles.length === 0 || this.$refs['upload'].uploadFiles[0].raw.type !== 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') {
        callback(new Error('请选择正确的文件'))
      }
      callback()
    }
    return {
      rules: {
        school: [
          { validator: validateSchoolId, trigger: 'blur' }
        ],
        date: [{ required: true, message: '测试日期不能为空', trigger: 'change' }],
        file: [{ validator: validateFile, trigger: 'blur' }]
      },
      tableHeight: '0px',
      errData: [],
      loading: false,
      uploadDialog: {
        show: false
      },
      data: {
        provinceId: 11,
        cityId: 1101,
        areaId: 11011,
        schoolId: '',
        date: ''
      },
      province: [],
      school: [],
      city: [],
      area: [],
      resultDialog: {
        show: false,
        valid: '',
        insertStudent: '',
        updateStudent: '',
        exemption: '',
        missing: '',
        result: '',
        insert: '',
        update: '',
        title: ''
      }
    }
  },
  methods: {
    submitCheck () {
      if (typeof this.$refs['form'] === 'undefined') {
        this.$message.error('请选择文件')
      } else {
        this.$refs['form'].validate((valid) => {
          if (valid) {
            this.loading = true
            physicalImportCheck(this.$refs['upload'].uploadFiles[0].raw, this.data.date, this.data.schoolId).then(res => {
              this.loading = false
              this.resultDialog.result = res.data.result
              this.resultDialog.valid = res.data.valid
              this.resultDialog.insertStudent = res.data.insertStudent
              this.resultDialog.updateStudent = res.data.updateStudent
              this.resultDialog.missing = res.data.missing
              this.resultDialog.exemption = res.data.exemption
              this.resultDialog.insert = res.data.insert
              this.resultDialog.update = res.data.update
              this.resultDialog.title = '检查结果'
              this.errData = res.data.errorMsg
              this.resultDialog.show = true
            })
          } else {
            this.$message.error('数据有误')
          }
        })
      }
    },
    submitImport () {
      if (typeof this.$refs['form'] === 'undefined') {
        this.$message.error('请选择文件')
      } else {
        this.$refs['form'].validate((valid) => {
          if (valid) {
            this.loading = true
            physicalImportSubmit(this.$refs['upload'].uploadFiles[0].raw, this.data.date, this.data.schoolId).then(res => {
              this.loading = false
              this.resultDialog.result = res.data.result
              this.resultDialog.valid = res.data.valid
              this.resultDialog.insertStudent = res.data.insertStudent
              this.resultDialog.updateStudent = res.data.updateStudent
              this.resultDialog.missing = res.data.missing
              this.resultDialog.exemption = res.data.exemption
              this.resultDialog.insert = res.data.insert
              this.resultDialog.update = res.data.update
              this.resultDialog.title = '导入结果'
              this.errData = res.data.errorMsg
              this.resultDialog.show = true
            })
          } else {
            this.$message.error('数据有误')
          }
        })
      }
    },
    submitUploadDialog () {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          this.uploadDialog.show = false
        } else {
          return false
        }
      })
    },
    reInitTableHeight () {
      if (document.documentElement.clientHeight - 40 - this.$refs['table_container'].$el.offsetTop < 0) {
        setTimeout(this.reInitTableHeight, 10)
      } else if (document.documentElement.clientHeight - 40 - this.$refs['table_container'].$el.offsetTop <= 500) {
        this.tableHeight = '500px'
      } else {
        this.tableHeight = document.documentElement.clientHeight - 40 - this.$refs['table_container'].$el.offsetTop + 'px'
      }
    }
  },
  computed: {
    ...mapGetters([
      'height'
    ])
  },
  watch: {
    height: function (val) {
      this.reInitTableHeight()
    },
    'data.provinceId': {
      handler () {
        GetCityListByProvinceId(this.data.provinceId).then(res => {
          this.city = res.data.city
          this.data.cityId = res.data.city[0].id
        })
      },
      immediate: true,
      deep: true
    },
    'data.cityId': {
      handler () {
        GetAreaListByCityId(this.data.cityId).then(res => {
          this.area = res.data.area
          this.data.areaId = res.data.area[0].id
        })
      },
      immediate: true,
      deep: true
    },
    'data.areaId': {
      handler () {
        GetSchoolListByAreaId(this.data.areaId).then(res => {
          this.school = res.data.school
          if (res.data.school.length === 0) {
            res.data.schoolId = ''
          } else {
            this.data.schoolId = res.data.school[0].id
          }
        })
      },
      immediate: true,
      deep: true
    }
  }
}
</script>

<style scoped>
  .right {
    display: flex;
    justify-content: flex-end;
    flex-grow:1;
  }
  .success-icon {
    font-size: 50px;
    color: #67C23A;
  }
  .error-icon {
    font-size: 50px;
    color: #F56C6C;
  }
  .center {
    text-align: center;
  }
  .result-text {
    display: flex;
    justify-content: space-between;
    width: 200px;
  }
  .flex-center {
    display: flex;
    justify-content: center;
  }
</style>
